"""用户账号相关的功能 注册 登录 短信 注销"""
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect

from web import models
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSMSForm, LoginForm
import uuid
import datetime


def register(request):
    """注册"""
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过，数据写入数据库(密码密文).相当于models.UserInfo.objects.create(**form.cleaned_data),然后剔除不需要的字段如confirm_password、code
        # form.instance.password = 'sfsdaf323e4r5t332344rff'也可以加密
        # 用户表中新建一条数据
        instance = form.save()
        policy_obj = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
        # 创建交易记录
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=policy_obj,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )

        return JsonResponse({'status': True, 'data': '/login/sms/'})
    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """发送短信"""
    form = SendSmsForm(request, data=request.GET)
    # 只是校验手机号不能为空、格式是否正确
    if form.is_valid():
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """短信登录"""
    if request.method == 'GET':
        form = LoginSMSForm()
        return render(request, 'login_sms.html', {'form': form})

    form = LoginSMSForm(request.POST)
    if form.is_valid():
        # 用户输入正确,登陆成功
        mobile_phone = form.cleaned_data['mobile_phone']
        # 用户信息放入session
        user_obj = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        request.session['user_id'] = user_obj.id
        request.session['user_name'] = user_obj.username
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({'status': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    """用户名和密码登录"""
    if request.method == "GET":
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        # user_obj = models.UserInfo.objects.filter(username=username, password=password).first()
        # (手机号=username and pwd=pwd) or (邮箱=username and pwd=pwd)
        from django.db.models import Q

        user_obj = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()

        if user_obj:
            # 用户名密码正确进行跳转
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('index')
        form.add_error('username', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


def image_code(request):
    """生成图片验证码"""
    from utils.image_code import check_code
    from io import BytesIO

    image_object, code = check_code()
    # 将验证码存入session并设置过期时间60秒
    request.session['image_code'] = code
    request.session.set_expiry(60)
    # 将图片放入内存
    stream = BytesIO()
    image_object.save(stream, 'png')

    return HttpResponse(stream.getvalue())


def logout(request):
    """退出登录，清空session，跳转到首页"""
    request.session.flush()
    return redirect('index')
